package com.tiansheng.microservice.authcenter.business.service;

import com.tiansheng.microservice.authcenter.business.domain.MemberDetails;
import com.tiansheng.microservice.mgb.mapper.TCauserMapper;
import com.tiansheng.microservice.mgb.model.TCauser;
import com.tiansheng.microservice.mgb.model.TCauserExample;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 
 *
 * @类描述：认证服务器加载用户的类
 *
 * @创建人：zhanghr
 *
 * @创建时间：2021年7月16日 下午1:20:06
 *
 *
 */
@Slf4j
@Component
public class MyUserDetailService implements UserDetailsService {

    /**
     * 方法实现说明:用户登陆
     * @param userName 用户名密码
     * @return: UserDetails
     * @exception:
     */

  //  @Autowired
 //   private UmsMemberMapper memberMapper;
    
    @Autowired
    private TCauserMapper causerMapper;
    
    

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        if(StringUtils.isEmpty(userName)) {
            log.warn("用户登陆用户名为空:{}",userName);
            throw new UsernameNotFoundException("用户名不能为空");
        }

        TCauser umsMember = getByUsername(userName);

        if(null == umsMember) {
            log.warn("根据用户名没有查询到对应的用户信息:{}",userName);
        }

        log.info("根据用户名:{}获取用户登陆信息:{}",userName,umsMember);

        MemberDetails memberDetails = new MemberDetails(umsMember);

        return memberDetails;
    }

    /**
     * 方法实现说明:根据用户名获取用户信息
     * @param username:用户名
     * @exception:
     */
    public TCauser getByUsername(String username) {
    	TCauserExample example = new TCauserExample();
    	example.createCriteria().andCodeEqualTo(username);
        List<TCauser> memberList = causerMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }
}
